<!DOCTYPE html>
<html  class="x-admin-sm">
<#include "../layout/meta.ftl">
<link rel="stylesheet" href="http://cdn.bootcss.com/materialize/0.97.0/css/materialize.min.css">
<body class="layui-layout-body">
<div class="layui-container" style="margin-top: 15px">
    <div class="layui-col-md12">
        <div class="layui-card"  style="font-size: 15px">
            <div class="layui-card-header"><b>${detail.name}</b></div>
            <div class="layui-card-body">
                <div class="row" style="color: chocolate">
                    <div class="col s12">
                        <div class="card">
                            <div class="card-content">
                                <p>名称：${detail.name}</p>
                                <p>UUID：<span id="text-uuid">${detail.uuid}</span></p>
                                <#if detail.ports??>
                                    <p>端口关系：${detail.ports}</p>
                                </#if>
                                <#if detail.imageTag??>
                                    <p>镜像Tag：${detail.imageTag}</p>
                                </#if>
                                <#if detail.dockerFilePath??>
                                    <p>DockerFile 路径：${detail.dockerFilePath}</p>
                                </#if>
                                <#if detail.dockerFileName??>
                                    <p>DockerFile 名字：${detail.dockerFileName}</p>
                                </#if>
                                <#if detail.volume??>
                                    <p>数据卷关系：${detail.volume}</p>
                                </#if>
                                <#if detail.url??>
                                    <p>GIT地址：${detail.url}</p>
                                </#if>
                                <#if detail.branch??>
                                    <p>GIT分支：${detail.branch}</p>
                                </#if>
                                <p>WEBHOOK自动部署地址：<span id="text-uuid1">/deploy/deploy/${detail.uuid}</span></p>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card-body">
                <div class="card-action" style="margin:20px">
                    <button type="button" class="layui-btn" data-type="deploy">手动部署</button>
                    <button type="button" class="layui-btn layui-btn-normal" data-type="restart">启动</button>
                    <button type="button" class="layui-btn layui-btn-warm" data-type="stop">停止</button>
                    <button type="button" class="layui-btn layui-btn-danger" data-type="removeProject">删除</button>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-md12" style="margin-top: 10px;">
        <div class="layui-card">
            <div class="layui-card-header"><b style="font-size: 15px">运行状态</b></div>
            <div class="layui-card-body" id="service-status" style="font-size: 10px;color: darkcyan">

            </div>
        </div>
    </div>

    <div class="layui-col-md12" style="margin-top: 10px;">
        <div class="layui-card">
            <table class="layui-table">
                <colgroup>
                    <col width="280">
                    <col width="100">
                    <col width="150">
                    <col width="200">
                    <col width="100">
                    <col>
                </colgroup>
                <thead>
                <tr>
                    <td>构建ID</td>
                    <td>部署状态</td>
                    <td>镜像ID</td>
                    <td>创建时间</td>
                    <td>构建耗时</td>
                    <td>详情</td>
                </tr>
                </thead>
                <tbody>
                <#list recordList as item>
                    <div id="desc${item_index}" class="modal modal-fixed-footer desc_data" style="z-index: 1000;top: 10%">
                        <div class="modal-content">
                            <pre><code id="show${item_index}">${item.desc}</code></pre>
                        </div>
                        <div class="modal-footer">
                            <a  onclick="$('#desc${item_index}').hide()" class="modal-action modal-close waves-effect waves-green btn-flat">关闭</a>
                        </div>
                    </div>
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.status}</td>
                        <#if item.imageId??>
                            <td>${item.imageId}</td>
                        <#else>
                            <td>暂时未知</td>
                        </#if>
                        <#if item.startTime??>
                            <td class="showTime">${item.startTime}</td>
                        <#else>
                            <td>暂时未知</td>
                        </#if>
                        <#if item.endTime??>
                            <td>${item.endTime-item.startTime}/s</td>
                        <#else>
                            <td>暂时未知</td>
                        </#if>
                        <td>
                            <button lay-data="${item.id}" type="button"  data-type="log" class="layui-btn log">日志</button>
                            <button lay-data="${item_index}" type="button"  data-type="desc" class="layui-btn desc">原因</button>
                            <button lay-data="${item.id}" type="button"  data-type="rollback" class="layui-btn rollback">回滚</button>
                            <button lay-data="${item.id}" type="button"  data-type="download" class="layui-btn download">下载</button>
                            <button lay-data="${item.id}" type="button"  data-type="remove" class="layui-btn remove">删除</button>
                        </td>
                    </tr>
                </#list>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    //JavaScript代码区域
    layui.use('element', function(){
        let element = layui.element;
        let uuid = $("#text-uuid").html();
        refreshStatus();
        //加载状态
        function refreshStatus() {
            $.ajax({
                url: "/deploy/status",
                type: "POST",
                data: {uuid: uuid},
                cache: false,
                success: function (data) {
                    let res = "状态：" + data.data.status + "<br>";
                    res += "镜像ID：" + data.data.imageId + "<br>";
                    res += "容器ID：" + data.data.id + "<br>";
                    res += "日志路径：" + data.data.logPath + "<br>";
                    res += "创建时间：" + data.data.created + "<br>";
                    $("#service-status").html(res).show();
                },
                error: function () {
                    layer.alert("发生异常，请重试！");
                }
            });
        }
        //时间处理
        $(".showTime").each(function(){
            let reg = new RegExp( ',' , "g" )
            $(this).text(formatDate(parseInt($(this).text().replace(reg,""))));
        });
        function formatDate(str) {
            let now=new Date(str*1000);
            let year=now.getFullYear();
            let month=now.getMonth()+1;
            let date=now.getDate();
            let hour=now.getHours();
            let minute=now.getMinutes();
            let second=now.getSeconds();
            return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
        }
        let active = {
            //查看日志
            log: function () {
                openWin($(this).attr("lay-data"));
            },
            desc: function () {
                try {
                    debugger;
                    let newData = JSON.stringify(JSON.parse($("#show"+$(this).attr("lay-data")).text()), null, 4);
                    $("#show"+$(this).attr("lay-data")).text(newData);
                }catch (e) {
                    console.log(e)
                }
                $("#desc"+$(this).attr("lay-data")).show();
            },
            rollback: function () {
                layer.alert("确定回滚到上次运行版本",function () {
                    rollBack("/deploy/rollback/" + uuid + "/" + $(this).attr("lay-data"));
                });
            },
            download: function () {
                location.href = "/deploy/downloadLog/" + $(this).attr("lay-data");
            },
            remove: function () {
                let conuuid=$(this).attr("lay-data");
                layer.alert("确定删除该容器",function () {
                    getAction("/deploy/remove/"+ conuuid,function () {
                        location.href = "/project/projectDesc/" + uuid;
                    });
                });
            },
            deploy:function () {
                deployData("/deploy/deploy/"+uuid);
            },
            restart: function () {
                ajaxShell("/deploy/restart", {uuid: uuid}, function () {
                    refreshStatus();
                });
            },
            stop:function () {
                ajaxShell("/deploy/stop", {uuid: uuid}, function () {
                    refreshStatus();
                });
            },
            removeProject: function () {
                layer.alert("确定删除当前容器",function () {
                    ajaxShell("/deploy/remove", {uuid: uuid}, function () {
                        refreshStatus();
                    });
                });

            }

        };
        function deployData(url) {
            $.ajax({
                url: url,
                type: "POST",
                cache: false,
                success: function (data) {
                    refreshStatus();
                    openWin(data.recordId);
                },
                error: function () {
                    refreshStatus();
                    openWin("发生异常，请重试！");
                }
            });
        };
        function getAction(url,func) {
            $.ajax({
                url: url,
                type: "get",
                cache: false,
                success: function (data) {
                    func();
                },
                error: function () {
                    layer.msg("删除失败")
                }
            });
        };
        function openWin(recordId){
            let url = "ws://" + location.host + "/ws";
            let websocket = new WebSocket(url);
            //多窗口模式，层叠置顶
            layer.open({
                type: 1
                ,title: '日志' //不显示标题栏
                ,closeBtn: false
                ,area: ['900px', '500px']
                ,shade: 0.8
                ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
                ,btn: ['关闭']
                ,btnAlign: 'c'
                ,moveType: 1 //拖拽模式，0或者1
                ,content:' <pre id="layer-modal" class="layui-code" style="background-color: black;color: cornsilk;height: 900px">' +''+'</pre>'
                ,success: function( layero){
                    websocket.onmessage = function (event) {
                        let msg = event.data;
                        let s = JSON.parse(msg);
                        if (s.type == "record") {
                            $("#layer-modal").html(s.msg);
                        }
                    };
                    websocket.onopen = function (event) {
                        if (recordId != null) {
                            //向服务器订阅部署消息
                            websocket.send("{\"record_id\":\"" + recordId + "\",\"type\":\"log\"}")
                        }
                    }
                }
                ,btn1: function(){
                    websocket.close();
                    layer.closeAll();
                }

            });
        };
        function rollBack(Url) {
            $.ajax({
                url: Url,
                type: "GET",
                cache: false,
                success: function (data) {
                    location.reload();
                },
                error: function () {
                    layer.msg("发生异常，请重试！");
                }
            });
        };
        function ajaxShell(url, postData, successCallback) {
            debugger;
            $.ajax({
                url: url,
                type: "POST",
                data: postData,
                cache: false,
                dataType: "text",
                success: function (data) {
                    layer.alert(data.replace(/\n/g, "<br>"));
                    if (successCallback) {
                        successCallback();
                    }
                },
                error: function () {
                    layer.alert("发生异常，请重试！");
                }
            });
        };
        $('.layui-btn').on('click', function () {
            let type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });
</script>
</body>
</html>